
/*
 * Este es el archivo que define los servicios usados en nuestra aplicación...
 * hay algunos que no veremos con detalle, ya que su propósito es especifico...
 * 
 * */
angular.module('eduApp.services', ['angularFileUpload'])
	.config(function($httpProvider) {
		  var interceptor = ['$q', '$window', '$location', '$injector', function($q, $window, $location, $injector) {
	        return {
	            request: function (config) {
	                config.headers = config.headers || {};
	                if ($window.sessionStorage.token) {
	                    config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
	                }//End of condition...
	                return config;
	            },

	            requestError: function(rejection) {
	                return $q.reject(rejection);
	            },

	            response: function (response) {
	                return response || $q.when(response);
	            },

	            // Revoke client authentication if 401 is received
	            responseError: function(rejection) {
	                console.log(rejection);
	                // Dynamically get the service since they can't be injected into config (AuthenticationService)
	                var AuthenticationService = $injector.get('AuthService');
	                if (rejection != null && rejection.status === 401 && ($window.sessionStorage.token || AuthenticationService.isLogged)) {
	                    delete $window.sessionStorage.token;
	                    AuthenticationService.isLogged = false;
	                    AuthenticationService.logout();
	                    $location.path("/");
	                }//End of condition...
	                return $q.reject(rejection);
	            }//End of function...
	        };
		}];
		  
	    //$httpProvider.interceptors.push(interceptor);
	    //$httpProvider.responseInterceptors.push('TCCHttpInterceptor');
    
	    $httpProvider.interceptors.push(['$injector',
	         function ($injector) {
             	return $injector.get('AuthInterceptor');
         	 }//fin de la funcion...
        ]);
	    
	    var spinnerFunction    = function(data, headersGetter) {
		  if($('body #loading-backdrop').length <= 0) {
	         $('body').append(
				 '<div id="loading-backdrop">' +
	             '  <div id="loading">' +
	             '    Cargando <i class="ion-loading-c"></i>' +
	             '  </div>' +
	             '</div>');
	      }//fin de la condicion...
	      return data;
	    };

	    //$httpProvider.defaults.transformRequest.push(spinnerFunction);
		//$httpProvider.defaults.transformResponse.push(spinnerFunction);
	})
	  
	.factory('AuthInterceptor', function ($rootScope, $q, AUTH_EVENTS) {
	     return {
	         responseError: function (response) { 
	            $rootScope.$broadcast({
	              401 : AUTH_EVENTS.notAuthenticated,
	              403 : AUTH_EVENTS.notAuthorized,
	              419 : AUTH_EVENTS.sessionTimeout,
	              440 : AUTH_EVENTS.sessionTimeout
	            }[response.status], response);
	            return $q.reject(response);
	         }//fin de la funcion...
	     };
	})
	
	.service('Session', function($rootScope, USER_ROLES) {
	     this.create           = function (sessionId, userId, userRole) {
	        this.id            = sessionId;
	        this.userId        = userId;
	        this.userRole      = userRole;
	     };
	     this.destroy          = function () {
	        this.id            = null;
	        this.userId        = null;
	        this.userRole      = null;
	     };
	     return this;
	})	
	  
	.factory('TCCHttpInterceptor', function ($q, $window) {
	      return function(promise) {
	         return promise.then(
				function(response) {
	              if($('body #loading-backdrop').length) {
	                 $('body #loading-backdrop').remove();
	              }//end of condition...
	              return response;
	            },
	            function (response) {
	              alert('Algo anda mal!');
	              return $q.reject(response);
	            }//fin de la funcion...
	         );
	      };
	})
	  
	/*
	 * Este factory o servicio es el que vamos a usar con frecuencia...
	 * ya que este es el de peticiones AJAX...
	 * */
	.factory('HTTP', ['$http', '$timeout', '$upload', '$modal', '$q', function($http, $timeout, $upload, $modal, $q) {
	    var API                    = {};
	    	
	    	/*
	    	 * Metodo para llamar ventanas emergentes...
	    	 * */
	        API.createModal        = function(config) {
			    return ($modal(config));
		    }//fin de la funcion...
	
	        /*
	         * Metodos para subir archivos al servidor...
	         * */
	        API.uploadFileServer   = function(config) {
		       return $upload.upload(config);	
		    }//fin de la funcion...
	
	        /*
	         * Metodo para hacer peticiones AJAX...
	         * */
	        API.requestServer      = function(URLaddress, paramsQuery) {
	          return $http({
	                       method  : 'POST',
	                       url     : URLaddress,
			               data    : paramsQuery,
	                       headers : {'Content-Type': 'application/x-www-form-urlencoded'},
	              transformRequest : function(obj) {
	                return Param(obj);
	            }//fin de la funcion...
	          });
	        }//fin de la funcion...
	
	        return API;
	}])
  
;